package cn.eng.order.service.impl;

import cn.eng.basic.utils.AjaxResult;
import cn.eng.order.domain.OrderPetAcquisition;
import cn.eng.order.dto.OrderDto;
import cn.eng.order.mapper.OrderPetAcquisitionMapper;
import cn.eng.order.service.IOrderPetAcquisitionService;
import cn.eng.basic.service.impl.BaseServiceImpl;
import cn.eng.pet.domain.Pet;
import cn.eng.pet.domain.PetType;
import cn.eng.pet.domain.SearchMasterMsg;
import cn.eng.pet.mapper.PetMapper;
import cn.eng.pet.mapper.SearchMasterMsgMapper;
import org.mockito.internal.matchers.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * 业务实现类：
 */
@Service
@SuppressWarnings("all")
public class OrderPetAcquisitionServiceImpl extends BaseServiceImpl<OrderPetAcquisition> implements IOrderPetAcquisitionService {

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private PetMapper petMapper;
    /**
     * 取消订单
     * @param id
     */
    @Transactional
    @Override
    public void cancel(Long id) {
        //查询订单
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadById(id);
        //shop_id置空
        searchMasterMsgMapper.reject(order.getSearchMasterMsgId());
        //设置订单状态
        order.setState(-1);
        orderPetAcquisitionMapper.update(order);

    }

    /**
     * 确认订单
     * @param orderDto
     */
    @Override
    @Transactional
    public void confirm(OrderDto orderDto) {
        //获取订单对象
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadById(orderDto.getId());
        //通过订单对象里面的寻主消息id 获取寻主消息对象
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(order.getSearchMasterMsgId());
        //生成宠物信息
        Pet pet = msg2Pet(msg,orderDto.getMoney());
        //添加pet
        petMapper.save(pet);
        //完善订单信息
        order.setPaytype(orderDto.getPayType());
        order.setPrice(orderDto.getMoney());
        order.setState(1);
        order.setPetId(pet.getId());
        orderPetAcquisitionMapper.update(order);
        //修改寻主消息 状态
        msg.setState(2);
        searchMasterMsgMapper.update(msg);

    }

    private Pet msg2Pet(SearchMasterMsg msg, BigDecimal money) {
        //获取pet对象
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(money);
        pet.setTypeId(msg.getPetType());
        pet.setState(0);
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }
}
